<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let o = {
      name: 'tom'
    }

    function fn() {
      console.log(this)
    }

    fn()  //此时什么都不加，this指向的是windows

    let o2 = {
      name: 'tom'
    }

    function fn2() {
      console.log(this)
    }
    // 使用apply方法之后，会改变this的指向
    fn2.apply(o2)

    let o3 = {
      name: 'tom'
    }

    function fn3(a, b) {
      console.log(this)
      console.log(a + b);
    }
    // 使用call方法之后，会改变this的指向
    fn3.apply(o3, [1, 2])

    // apply方法
    function Student2(theName, theAge) {
      this.name = theName;
      this.age = theAge
    }
    var stu2 = { className: '113期' }
    Student2.apply(stu2, ['小白', 24])
    console.log(stu2); // {className: "113期", name: "小白", age: 24}

    // apply的应用 利用apply,借助于数学内置对象求最大值Math.max()
    let arr = [1, 66, 3, 99, 4]
    // 不需要改变this指向，那就传递一个null
    // 但是一般不能传null,会报错，可以把Math自身传递过去
    // let max = Math.max.apply(null, arr)
    let max = Math.max.apply(Math, arr)
    let min = Math.min.apply(Math, arr)
    let max2 = Math.max(...arr)
    let min2 = Math.min(...arr)
    console.log(max, min, max2, min2);


    function Father(name, age, sex) {
      this.name = name
      this.age = age
      this.sex = sex
    }
    function Son(name, age, sex) {
      // 这里使用son中的this，替换father中的this
      Father.apply(this, [name, age, sex])
    }

    let son = new Son('tom', 18, '男')
    console.log(son);

    function Pet2(words) {
      this.words = words;
      this.speak = function () {
        console.log(this.words)
      }
    }
    function Dog2(words) {
      //Pet.call(this, words); //结果： Wang
      Pet2.apply(this, arguments); //结果： Wang
    }
    var dog = new Dog2('Wang');
    dog.speak();
  </script>
</body>

</html>